package 网络编程.tcp;

import 网络编程.Log;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient {
    public static void main(String[] args) throws Exception{
        //客户端不需要SeverSocket，直接创建Socket对象
        //1，创建Socket并将其连接到指定的IP下的指定端口，即连接到服务器
        Log.println("准备与服务器创建连接");
        Socket socket = new Socket("127.0.0.1",9999);

        InputStream inputStream = socket.getInputStream();
        Scanner socInput = new Scanner(inputStream,"UTF-8");

        OutputStream outputStream = socket.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
        PrintWriter writer = new PrintWriter(outputStreamWriter);

        Log.println("连接建立成功，请输入英文：");
        //2，输入请求
        Scanner sc = new Scanner(System.in);
        while (true){
            if (!sc.hasNextLine()){
                break;
            }
            String engWord = sc.nextLine();
            String request = engWord + "\r\n";

            //3，将请求保存到输出流,发送请求
            Log.println("准备发送请求");
            writer.write(request);
            writer.flush();
            Log.println("请求发送成功");

            //4,接受响应
            Log.println("准备接受响应");
            String response = socInput.nextLine();//nextLine返回的值，直接将换行去掉
            Log.println("请求：" + engWord);
            Log.println("响应：" + response);
        }
        //5，关闭资源
        socket.close();
        Log.println("关闭资源");
    }
}
